package com.ocom.aiot.controller;

import com.ocom.aiot.service.RoleInfoService;
import com.ocom.aiot.service.UserRolesService;
import com.ocom.aiot.vo.accessdevice.GetDeviceInfoVo;
import com.ocom.common.constant.AiotUrl;
import com.ocom.common.entity.aiot.EntityRoleInfo;
import com.ocom.common.entity.aiot.EntityUserRoles;
import com.ocom.common.enums.ResultEnum;
import com.ocom.common.resp.Result;
import com.ocom.common.utils.ResultUtil;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@RestController
public class UserRoleController {
    private final Logger log = LoggerFactory.getLogger(UserRoleController.class);

    @Autowired
    private RoleInfoService roleInfoService;

    @Autowired
    private UserRolesService userRolesService;

    // 2.3.5.获取用户角色列表（getUserRoleByUserId）
    @GetMapping(AiotUrl.URL_Aiot_GetUserRoleByUserId)
    public Result GetUserRoleByUserId(Long userId){
        if (userId == null){
            log.error("用户id为空");
            return ResultUtil.error(ResultEnum.Err_203,"用户id为空");
        }
        Map<String, Object> map = new HashMap<>();
        List<EntityUserRoles> entityUserRoles = null;
        try {
            entityUserRoles = userRolesService.GetUserRoles(userId);
        }catch (Exception exception){
            log.error("查询用户权限列表集合为空："+exception.getMessage());
            return ResultUtil.error(ResultEnum.Err_2009,"查询用户权限列表集合为空");
        }
        if (entityUserRoles == null){
            log.error("用户权限列表数据为空");
            return ResultUtil.error(ResultEnum.Err_1000,"用户权限列表数据为空");
        }
        List<EntityRoleInfo> entityRoleInfos = null;
        try {
            List<Long> roleId = entityUserRoles.stream().map(EntityUserRoles::getRoleId).collect(Collectors.toList());
            List<Long> userIds = entityUserRoles.stream().map(EntityUserRoles::getUserId).collect(Collectors.toList());
            map.put("userId",userIds);
            map.put("roleId",roleId);
            entityRoleInfos = roleInfoService.GetRoleInfos(roleId);
            List<String> roleName = entityRoleInfos.stream().map(EntityRoleInfo::getRoleName).collect(Collectors.toList());
            map.put("roleName",roleName);

        }catch (Exception exception){
            log.error("获取权限列表失败："+exception.getMessage());
            return ResultUtil.error(ResultEnum.Err_2009,"获取权限列表失败");

        }
        return ResultUtil.success(map);
    }


}
